package com.jzo2o.trade.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.trade.enums.RefundStatusEnum;
import com.jzo2o.trade.mapper.RefundRecordMapper;
import com.jzo2o.trade.model.domain.RefundRecord;
import com.jzo2o.trade.model.domain.Trading;
import com.jzo2o.trade.service.IRefundRecordService;
import com.jzo2o.trade.service.ITradingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * \* User: chy
 * \* Date: 2025/10/9  9:43
 * \* Description:
 * \
 */
@Service
@Slf4j
public class RefundRecordServiceImpl extends ServiceImpl<RefundRecordMapper, RefundRecord> implements IRefundRecordService {

    @Autowired
    private ITradingService tradingService;

    /**
     * 创建退款记录
     *
     * @param tradingOrderNo
     * @param refundAmount
     * @return
     */
    @Override
    public RefundRecord saveRefundRecord(Long tradingOrderNo, BigDecimal refundAmount) {
        // 查询支付订单
        Trading trading = tradingService.getOne(Wrappers.<Trading>lambdaQuery()
                .eq(Trading::getTradingOrderNo, tradingOrderNo));
        if(trading == null){
            log.error("支付订单不存在:{}", tradingOrderNo);
            return null;
        }
        if(refundAmount.compareTo(trading.getTradingAmount()) > 0){
            log.error("退款金额不能大于支付金额:{}", tradingOrderNo);
            throw new RuntimeException("退款金额不能大于支付金额");
        }
        // 创建退款记录
        RefundRecord refundRecord = new RefundRecord();
        // 订单单号
        refundRecord.setTradingOrderNo(tradingOrderNo+ "");
        // 业务系统订单号
        refundRecord.setProductOrderNo(trading.getProductOrderNo());
        // 本次退款的金额
        refundRecord.setRefundAmount(refundAmount);
        // 本次退款单号
        refundRecord.setRefundNo(Long.parseLong(tradingOrderNo+ ""+ RandomUtil.randomInt(1,10)));
        // 退款渠道
        refundRecord.setTradingChannel(trading.getTradingChannel());
        // 退款状态
        refundRecord.setRefundStatus(RefundStatusEnum.APPLY_REFUND.getCode());
        // 原订单金额
        refundRecord.setTotal(trading.getTradingAmount());
        save(refundRecord);
        return refundRecord;
    }
}
